function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function showAlert(msg, cb) {
  wx.showModal({
    //title: '提示',
    content: msg,
    showCancel: false,
    success: function(res) {
      if (res.confirm) {
        cb && cb();
      }
    }
  })
}

function showConfirm(msg, cb, cancelCb) {
  wx.showModal({
    //title: '提示',
    content: msg,
    showCancel: true,
    success: function(res) {
      if (res.confirm) {
        cb && cb();
      } else if (res.cancel) {
        cancelCb && cancelCb();
      }
    }
  });
}

function showOK(msg) {
  wx.showToast({
    title: msg,
    icon: 'success',
    duration: 1500
  })
}

function doLoading() {
  wx.showLoading({
    title: '加载中',
    mask: false,
  });
  // wx.showToast({
  //   title: '加载中',
  //   icon: 'loading',
  //   //duration: 1200
  // })
}

function hideLoading() {
  wx.hideLoading();
}

/**
 * 扫描二维码进入时，根据scene进行跳转
 * @param  {[type]}
 * @return {[type]}
 */
function jumpByScene(scene) {
  if (!scene) {
    return false;
  }
  scene = decodeURIComponent(scene);

  if (scene) {
    wx.redirectTo({
      url: scene
    })
    return true;
  }
  return false;
}


// 调用微信支付接口
function wxPay(param) {
  wx.requestPayment({
    'timeStamp': param.timeStamp,
    'nonceStr': param.nonceStr,
    'package': param.package,
    'signType': 'MD5',
    'paySign': param.paySign,
    success: function(res) {
      typeof param.success === 'function' && param.success();
    },
    fail: function(res) {
      if (res.errMsg === 'requestPayment:fail cancel' || 'requestPayment:fail') {
        return;
      }
      showAlert(res.errMsg)
    }
  })
}

module.exports = {
  formatTime: formatTime,
  alert: showAlert,
  confirm: showConfirm,
  showOK: showOK,
  loading: doLoading,
  showLoading: doLoading,
  hideLoading: hideLoading,
  jumpByScene,
  wxPay,
}